package com.zzb.weikeautosign.client;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.regex.Pattern;

/**
 * socket服务器测试
 * Created by zzb on 16/3/4.
 */
public class SocketClient {
    static Pattern exitPattern = Pattern.compile("^(q|quit|exit|bye)$");
    Socket socket = null;
    BufferedWriter os = null;

    public void test(){
        Scanner scanner = new Scanner(System.in);
        String commend = null;
        String ret = null;
        try {
            socket = new Socket("127.0.0.1",29999);
            os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf8"));
            new SocketClientReceiver(socket).start();
            while (true){
                if (scanner.hasNext()){
                    commend = scanner.nextLine();
                    while (exitPattern.matcher(commend).matches()){
                        close();
                        System.out.println("关闭连接");
                        System.exit(0);
                    }
                    os.write(commend);
                    os.newLine();
                    os.flush();
                }
            }
        } catch (IOException e) {
            System.out.println("连接已关闭");
        } finally {
            close();
        }
    }
    private void close(){
        try {
            if(os != null) os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(socket!=null)socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new SocketClient().test();
    }
}
